<?php
/**
 * @ClassName: Merchant
 * @Description: 商户进件
 * @author: gydtrade
 * @Date: 2025-10-22 13:56
 * @Version: V1.0.0
 */

namespace app\common\huifu;

use app\common\model;
use think\facade\Log;

class Merchant
{
    protected $dataModel;
    protected $return_url;

    public function __construct()
    {
        Sdk::init(); //初始化sdk
        Log::init(['type' => 'File', 'path' => app()->getRuntimePath() . 'log' . DIRECTORY_SEPARATOR . 'huifu/merchant']);
        $this->dataModel = new model\huifu\HuifuCorpMember();
        $this->return_url = domain() . '/api/huifu/';//商户入驻回调地址
    }

    /**
     * 企业商户进件/修改（有营业执照的，包含个体户）
     * @param $data
     * @param $id
     * @return array
     */
    function companyApply($data, $id)
    {
        $client = new \BsPaySdk\core\BsPayClient();
        $req_seq_id = date("YmdHis") . mt_rand();
        if (isset($data['huifu_id']) && $data['huifu_id']) {
            // 组装请求参数
            // https://api.huifu.com/v2/merchant/basicdata/ent/modify
            $request = new \BsPaySdk\request\V2MerchantBasicdataModifyRequest();
            // 请求流水号
            $request->setReqSeqId($req_seq_id);
            // 请求日期
            $request->setReqDate(date("Ymd"));
            // 汇付客户Id
            $request->setHuifuId($data['huifu_id']);

            $extendInfoMap = $this->extendInfoMap($data, 1);

            $request->setExtendInfo($extendInfoMap);
            $result = $client->postRequest($request);

            if ($result->isError()) {
                //失败处理
                trace($result->getErrorInfo());

                $this->dataModel->where('id', $id)->update(['resp_desc' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)]);

                return ['code' => 0, 'msg' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)];
            } else {
                //成功处理
                $res = $result->getRspDatas();

                trace($res);

                if ($res && !is_string($res) && isset($res['data']) && isset($res['data']['resp_code'])) {

                    $resData = $res['data'];
                    if ($resData['resp_code'] == '00000000') {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc'], 'huifu_id' => $resData['huifu_id']]);
                        return ['code' => 1, 'msg' => $resData['resp_desc']];
                    } else {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc']]);
                        return ['code' => 0, 'msg' => $resData['resp_desc']];
                    }
                }
            }
        } else {
            // 组装请求参数
            // https://api.huifu.com/v2/merchant/basicdata/ent
            $request = new \BsPaySdk\request\V2MerchantBasicdataEntRequest();
            // 请求流水号
            $request->setReqSeqId($req_seq_id);
            // 请求日期
            $request->setReqDate(date("Ymd"));

            $extendInfoMap = $this->extendInfoMap($data, 1);

            $request->setExtendInfo($extendInfoMap);
            $result = $client->postRequest($request);

            if ($result->isError()) {
                //失败处理
                trace($result->getErrorInfo());

                $this->dataModel->where('id', $id)->update(['resp_desc' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)]);

                return ['code' => 0, 'msg' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)];
            } else {
                //成功处理
                $res = $result->getRspDatas();

                trace($res);

                if ($res && !is_string($res) && isset($res['data']) && isset($res['data']['resp_code'])) {
                    $resData = $res['data'];
                    if ($resData['resp_code'] == '00000000') {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc'], 'huifu_id' => $resData['huifu_id'], 'login_name' => $resData['login_name'] ?? '', 'login_password' => $resData['login_password'] ?? '']);
                        return ['code' => 1, 'msg' => $resData['resp_desc']];
                    } else {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc']]);
                        return ['code' => 0, 'msg' => $resData['resp_desc']];
                    }
                }
            }
        }

        return ['code' => 0, 'msg' => '处理失败'];
    }

    /**
     * 个人（小微）商户进件/修改
     * @param $data
     * @param $id
     * @return array
     */
    function personApply($data, $id)
    {
        $client = new \BsPaySdk\core\BsPayClient();
        $req_seq_id = date("YmdHis") . mt_rand();
        if (isset($data['huifu_id']) && $data['huifu_id']) {
            // 组装请求参数
            // https://api.huifu.com/v2/merchant/basicdata/indv/modify
            $request = new \BsPaySdk\request\V2MerchantBasicdataModifyRequest();
            // 请求流水号
            $request->setReqSeqId($req_seq_id);
            // 请求日期
            $request->setReqDate(date("Ymd"));
            // 汇付客户Id
            $request->setHuifuId($data['huifu_id']);

            $extendInfoMap = $this->extendInfoMap($data, 2);

            $request->setExtendInfo($extendInfoMap);
            $result = $client->postRequest($request);

            if ($result->isError()) {
                //失败处理
                trace($result->getErrorInfo());

                $this->dataModel->where('id', $id)->update(['resp_desc' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)]);

                return ['code' => 0, 'msg' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)];
            } else {
                //成功处理
                $res = $result->getRspDatas();

                trace($res);

                if ($res && !is_string($res) && isset($res['data']) && isset($res['data']['resp_code'])) {

                    $resData = $res['data'];
                    if ($resData['resp_code'] == '00000000') {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc'], 'huifu_id' => $resData['huifu_id']]);
                        return ['code' => 1, 'msg' => $resData['resp_desc']];
                    } else {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc']]);
                        return ['code' => 0, 'msg' => $resData['resp_desc']];
                    }
                }
            }
        } else {
            // 组装请求参数
            // https://api.huifu.com/v2/merchant/basicdata/indv
            $request = new \BsPaySdk\request\V2MerchantBasicdataIndvRequest();
            // 请求流水号
            $request->setReqSeqId($req_seq_id);
            // 请求日期
            $request->setReqDate(date("Ymd"));

            $extendInfoMap = $this->extendInfoMap($data, 2);

            $request->setExtendInfo($extendInfoMap);
            $result = $client->postRequest($request);

            if ($result->isError()) {
                //失败处理
                trace($result->getErrorInfo());

                $this->dataModel->where('id', $id)->update(['resp_desc' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)]);

                return ['code' => 0, 'msg' => json_encode($result->getErrorInfo(), JSON_UNESCAPED_UNICODE)];
            } else {
                //成功处理
                $res = $result->getRspDatas();

                trace($res);

                if ($res && !is_string($res) && isset($res['data']) && isset($res['data']['resp_code'])) {
                    $resData = $res['data'];
                    if ($resData['resp_code'] == '00000000') {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc'], 'huifu_id' => $resData['huifu_id'], 'login_name' => $resData['login_name'] ?? '', 'login_password' => $resData['login_password'] ?? '']);
                        return ['code' => 1, 'msg' => $resData['resp_desc']];
                    } else {
                        $this->dataModel->where('id', $id)->update(['resp_desc' => $resData['resp_desc']]);
                        return ['code' => 0, 'msg' => $resData['resp_desc']];
                    }
                }
            }
        }

        return ['code' => 0, 'msg' => '处理失败'];
    }

    //商户业务开通
    function businessOpen()
    {
        // https://api.huifu.com/v2/merchant/busi/open
    }

    //商户业务开通修改
    function businessModify()
    {
        // https://api.huifu.com/v2/merchant/busi/modify
    }

    //商户详细信息查询
    function queryInfo()
    {
        // https://api.huifu.com/v2/merchant/basicdata/query
    }

    //图片上传
    function uploadImg(){
        // https://api.huifu.com/v2/supplementary/picture
    }

    //申请单状态查询
    function applyStatus()
    {
        // https://api.huifu.com/v2/merchant/basicdata/status/query
    }

    //商户短信发送
    function sendSms(){
        // https://api.huifu.com/v2/merchant/basicdata/sms/send
    }

    //商户费率信息查询（支持指定费率类型查询）
    function queryFeeRate(){
        // https://api.huifu.com/v2/merchant/fee-rate/query
    }

    /**
     * 扩展数据
     * @param $data
     * @param $type
     * @return array
     */
    private function extendInfoMap($data, $type = 1)
    {
        if ($type == 1) {
            // 企业商户
            $extendInfoMap = [
                'reg_name' => $data['reg_name'],//商户名称
                'short_name' => $data['short_name'],//商户简称
                'receipt_name' => $data['short_name'],//小票名称
                'ent_type' => $data['ent_type'],//公司类型
                'mcc' => $data['busi_type'],//所属行业
                'busi_type' => $data['scene_type'],//经营类型，1：实体，2：虚拟
                'scene_type' => $data['scene_type'],//场景类型，ONLINE：线上场景；OFFLINE：线下场景；ALL：线上线下；
                'license_pic' => $data['license_pic'],//证照图片
                'license_code' => $data['license_code'],//证照编号
                'license_validity_type' => $data['license_validity_type'],//证照有效期类型
                'license_begin_date' => $data['license_begin_date'],//证照有效期开始日期
                'license_end_date' => $data['license_end_date'],//证照有效期截止日期
                'found_date' => $data['found_date'],//成立时间
                'reg_prov_id' => str_pad($data['reg_prov_id'], 6, '0', STR_PAD_RIGHT),//注册省
                'reg_area_id' => str_pad($data['reg_area_id'], 6, '0', STR_PAD_RIGHT),//注册市
                'reg_district_id' => str_pad($data['reg_district_id'], 6, '0', STR_PAD_RIGHT),//注册区
                'reg_detail' => $data['reg_detail'],//注册详细地址
                'prov_id' => str_pad($data['prov_id'], 6, '0', STR_PAD_RIGHT),//经营省
                'area_id' => str_pad($data['area_id'], 6, '0', STR_PAD_RIGHT),//经营市
                'district_id' => $data['district_id'],//经营区
                'detail_addr' => $data['detail_addr'],//经营详细地址
                'legal_name' => $data['legal_name'],//法人姓名
                'legal_cert_type' => $data['legal_cert_type'],//法人证件类型
                'legal_cert_no' => $data['legal_cert_no'],//法人证件号码
                'legal_cert_validity_type' => $data['legal_cert_validity_type'],//法人证件有效期类型
                'legal_cert_begin_date' => $data['legal_cert_begin_date'],//法人证件有效期开始日期
                'legal_cert_end_date' => $data['legal_cert_end_date'],//法人证件有效期截止日期
                'legal_mobile_no' => $data['contact_mobile'],//法人手机号
                'legal_addr' => $data['legal_addr'],//法人证件地址
                'legal_cert_back_pic' => $data['legal_cert_back_pic'],//法人身份证国徽面
                'legal_cert_front_pic' => $data['legal_cert_front_pic'],//法人身份证人像面
                'contact_name' => $data['contact_name'],//联系人姓名
                'contact_mobile_no' => $data['contact_mobile'],//联系人手机号
                'contact_email' => $data['contact_email'],//联系人电子邮箱
                'sms_send_flag' => $data['sms_send_flag'],//商户通知标识
                'login_name' => $data['login_name'],//管理员账号
                'reg_acct_pic' => $data['reg_acct_pic'],//开户许可证
                'open_licence_no' => $data['open_licence_no'],//基本存款账户编号或核准号
                'card_info' => $data['card_info'],//银行卡信息配置
                'settle_card_front_pic' => $data['settle_card_front_pic'],//结算卡正面
                'settle_cert_back_pic' => $data['settle_cert_back_pic'],//持卡人身份证国徽面
                'settle_cert_front_pic' => $data['settle_cert_front_pic'],//持卡人身份证人像面
                'auth_entrust_pic' => $data['auth_entrust_pic'],//授权委托书
                'store_header_pic' => $data['store_header_pic'],//店铺门头照
                'store_indoor_pic' => $data['store_indoor_pic'],//店铺内景/工作区域照
                'store_cashier_desk_pic' => $data['store_cashier_desk_pic'],//店铺收银台/公司前台照
                'async_return_url' => $this->return_url,//审核结果消息接收地址，为空时不推送消息
            ];
        } else {
            //个人商户
            $extendInfoMap = [
                'reg_name' => $data['reg_name'],//商户名称
                'short_name' => $data['short_name'],//商户简称
                'mcc' => $data['mcc'],//所属行业
                'scene_type' => $data['scene_type'],//场景类型，ONLINE：线上场景；OFFLINE：线下场景；ALL：线上线下；
                'prov_id' => str_pad($data['prov_id'], 6, '0', STR_PAD_RIGHT),//经营省
                'area_id' => str_pad($data['area_id'], 6, '0', STR_PAD_RIGHT),//经营市
                'district_id' => $data['district_id'],//经营区
                'detail_addr' => $data['detail_addr'],//经营详细地址
                'legal_cert_no' => $data['legal_cert_no'],//负责人证件号码
                'legal_cert_validity_type' => $data['legal_cert_validity_type'],//负责人证件有效期类型
                'legal_cert_begin_date' => $data['legal_cert_begin_date'],//负责人证件有效期开始日期
                'legal_cert_end_date' => $data['legal_cert_end_date'],//负责人证件有效期截止日期
                'legal_addr' => $data['legal_addr'],//负责人证件地址
                'legal_cert_back_pic' => $data['legal_cert_back_pic'],//负责人身份证国徽面
                'legal_cert_front_pic' => $data['legal_cert_front_pic'],//负责人身份证人像面
                'contact_mobile_no' => $data['contact_mobile'],//负责人手机号
                'contact_email' => $data['contact_email'],//负责人电子邮箱
                'sms_send_flag' => $data['sms_send_flag'],//商户通知标识
                'login_name' => $data['login_name'],//管理员账号
                'card_info' => $data['card_info'],//银行卡信息配置
                'settle_card_front_pic' => $data['settle_card_front_pic'],//结算卡正面
                'store_header_pic' => $data['store_header_pic'],//店铺门头照
                'store_indoor_pic' => $data['store_indoor_pic'],//店铺内景/工作区域照
                'store_cashier_desk_pic' => $data['store_cashier_desk_pic'],//店铺收银台/公司前台照
                'async_return_url' => $this->return_url,//审核结果消息接收地址，为空时不推送消息
            ];
        }

        return $extendInfoMap;
    }

}